#include "mainwindow.h"
#include "ui_mainwindow.h"
#include <QDebug>
#include <QRandomGenerator>
#include <QTime>
#include <QLabel>

MainWindow::MainWindow(QWidget *parent)
    : QMainWindow(parent)
    , ui(new Ui::MainWindow)
{
    ui->setupUi(this);
    qRegisterMetaType<TestData>("TestData");
    connect(&m_testQueue, &TestQueue::signalMoveData, this, &MainWindow::onMoveData, Qt::QueuedConnection);
}

MainWindow::~MainWindow()
{
    delete ui;
}

void MainWindow::on_pushButton_clicked()
{
    qsrand(QTime(0,0,0).secsTo(QTime::currentTime()));
    int x = QRandomGenerator::global()->bounded(ui->widget->width());
    int y = QRandomGenerator::global()->bounded(ui->widget->height());
    static int numb = 1;
    QString name = QString::number(numb);
    numb++;
    TestData data;
    data.pos = QPoint(x, y);
    data.strData = name;
    m_testQueue.pushDataToQueue(data);
}

QLabel* MainWindow::createRectangle()
{
    QLabel* label = new QLabel(ui->widget);
    label->setGeometry(0, 0, 30, 30);
    label->setStyleSheet("QLabel {"
    "  border-radius: 2px;"
    "  background-color: red;"
    "}"
    );
    label->show();
    return label;
}

void MainWindow::onMoveData(TestData data)
{
    QLabel* label = createRectangle();
    label->setText(data.strData);
    label->move(data.pos.x(), data.pos.y());
}

void TestQueue::pushDataToQueue(const TestData& transData)
{
    m_queue.enqueue(transData);
    if(!isRunning()){
        m_abort = false;
        start();
    }
    else
    {
        condition.wakeOne();
    }
}

void TestQueue::quitThread() {
    if(isRunning()){
        m_abort = true;
        condition.wakeOne();
        wait();
    }
}

void TestQueue::run()
{
    forever {
        if(m_abort) {
            break;
        }

        if(m_queue.size_approx() == 0) {
            m_lock.lock();
            condition.wait(&m_lock);
            m_lock.unlock();
        }
        else {
            TestData data;
            if(m_queue.wait_dequeue_timed(data, std::chrono::milliseconds(150))) {
                // 在线程中对数据进行处理，假设处理需要1s
                QThread::msleep(1000);
                // 处理完成发给界面响应
                emit signalMoveData(data);
            }
        }
    }
}




